package io.bitmax.exchange.base.service;

import java.io.File;
import java.util.concurrent.TimeUnit;

import io.bitmax.exchange.BuildConfig;
import io.bitmax.exchange.base.entity.BaseHttpResult;
import io.bitmax.exchange.base.http.HttpApi;
import io.bitmax.exchange.base.http.RetrofitHttpClient;
import io.bitmax.exchange.base.http.UnSafeHostnameVerifier;
import io.bitmax.library.core.BaseCoreApplication;
import io.bitmax.library.interceptor.LoggerIntercepter;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Cache;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * retrofit
 * Created by gongdongyang on 2018/9/25.
 */

public class RetrofitService {

    //private static final String API_HOST = "https://apptest.ccxcredit.com/appTest/v16/";
    private static final String API_HOST = BuildConfig.API_HOST_URL;

    private static HttpApi httpApi;

    public static void init(){
        // 指定缓存路径,缓存大小100Mb
        Cache cache = new Cache(new File(BaseCoreApplication.getInstance().getCacheDir(), "HttpCache"),
                1024 * 1024 * 100);
        RetrofitHttpClient.init(BaseCoreApplication.getInstance());
        RetrofitHttpClient.getInstance()
                .setConnectTimeout(60 * 1000)
                .setRetryCount(3)//默认网络不好自动重试3次
                .setRetryDelay(500)//每次延时500ms重试
                .setRetryIncreaseDelay(500)//每次延时叠加500ms
                .setCertificates()//信任所有证书
                .setHostnameVerifier(new UnSafeHostnameVerifier(API_HOST))//全局访问规则
                .setBaseUrl(API_HOST)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                //.addInterceptor(new CommonInterceptor())
                .addInterceptor(new LoggerIntercepter())
                .setOkclient(RetrofitHttpClient.getOkHttpClient());
        httpApi = RetrofitHttpClient.getRetrofit().create(HttpApi.class);
    }


    /**
     * 登录
     * @param loginName
     * @param password
     * @return
     */
    public static Observable<BaseHttpResult<String>> login(String loginName, String password){
        return applySchedulers(httpApi.login(loginName,password));
    }

    static <T> Observable<T>  applySchedulers(Observable<T> observable) {
        return observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread());
    }

}
